package com.emm.yixun.openapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.emm.yixun.common.app.BaseDataReqDto;
import com.emm.yixun.common.app.ProjectsPmoReqDto;
import com.emm.yixun.common.app.ProjectsPmoResDto;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.DictionaryTypeEnum;
import com.emm.yixun.common.model.enums.MerchantEnum;
import com.emm.yixun.common.model.pmo.LevelDynamiSalesData;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.openapi.constant.PmoConfig;
import com.emm.yixun.openapi.dto.base.BaseRequestDTO;
import com.emm.yixun.openapi.dto.base.BaseResponseDTO;
import com.emm.yixun.openapi.hander.*;
import com.emm.yixun.openapi.utils.RSAUtil;
import com.emm.yixun.openapi.vo.*;
import com.emm.yixun.system.service.DictionaryServiceFacade;
import com.emm.yixun.system.service.PmoLogServiceFacade;
import com.emm.yixun.system.service.pmo.PmoDynamicDataServiceFacade;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class ApiController {
	
	private static Logger logger = LoggerFactory.getLogger(ApiController.class);
	
	/**
	 * 绿城扩展
	 */
	@Autowired
	private QueryProjectInfoHander queryProjectInfoHander;
	@Autowired
	private QueryAgentInfoHander queryAgentInfoHander;
	@Autowired
	private QueryProjectRelationAgentInfoHander queryProjectRelationAgentInfoHander;
	@Autowired
	private QueryCustomerInfoHander queryCustomerInfoHander;
	@Autowired
	private QueryCustomerFollowInfoHander queryCustomerFollowInfoHander;
	@Autowired
	private PmoLogServiceFacade pmoLogServiceFacade;
	@Autowired
	private QueryProjectRoomInfoListHander queryProjectRoomInfoListHander;
	@Autowired
	private QueryCustomerRoomListHander queryCustomerRoomListHander;
	@Autowired
	private QueryCustomerTagListHander queryCustomerTagListHander;
	@Autowired
	private QueryCustomerQuestionnaireListHander queryCustomerQuestionnaireListHander;
	@Autowired
	private QueryAgentListByCustomerPhoneHander queryAgentListByCustomerPhoneHander;
	@Autowired
	private PmoDynamicDataServiceFacade pmoDynamicDataServiceFacade;

	/**
	 * 绿城扩展PMO
	 */
	@Autowired
	private QueryProjectInfoPomHander queryProjectInfoPomHander;
	/**
	 * 绿城扩展PMO
	 */
	@Autowired
	private ProjectsPmoHander projectsPmoHander;

	@Autowired
	private BaseDataHander baseDataHander;

	@Autowired
	private PmoConfig pmoConfig;

	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private PropertyFormsInvalidHander propertyFormsInvalidHander;

	@Autowired
	private DictionaryServiceFacade dictionaryServiceFacade;

	@Autowired
	private ChannelToM2Hander channelToM2Hander;

	@Autowired
	private OaOrgHander oaOrgHander;

	/**
	 * 新房、渠道接口
	 */
	@Autowired
	private MCQueryProjectHander mcQueryProjectHander;
	@Autowired
	private MCCusUniqueHander mcCusUniqueHander;

	/**
	 * 基本信息类接口（绿城扩展）
	 * 
	 * （1）项目信息全量查询接口(queryProjectInfo)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryProjectInfo")
	public String queryProjectInfo(Model model, HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryProjectInfoReqVo reqDto = JSONObject.parseObject(body, QueryProjectInfoReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryProjectInfoHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 * 
	 * （2）经纪人信息全量查询接口接口(queryAgentInfo)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryAgentInfo")
	public String queryAgentInfo(Model model, HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryAgentInfoReqVo reqDto = JSONObject.parseObject(body, QueryAgentInfoReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryAgentInfoHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			logger.error("queryAgentInfo error: ", e);
			e.printStackTrace();
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 * 
	 * （3）经纪人与项目的归属关系全量查询接口(queryProjectRelationAgentInfo)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryProjectRelationAgentInfo")
	public String queryProjectRelationAgentInfo(Model model, HttpServletRequest request, HttpServletResponse response,
			String body) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryProjectRelationAgentInfoReqVo reqDto = JSONObject.parseObject(body,
				QueryProjectRelationAgentInfoReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryProjectRelationAgentInfoHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryProjectRelationAgentInfo error: ", e);
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 * 
	 * （4）客户基本信息增量更新接口(queryCustomerInfo)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryCustomerInfo")
	public String queryCustomerInfo(Model model, HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryCustomerInfoReqVo reqDto = JSONObject.parseObject(body, QueryCustomerInfoReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryCustomerInfoHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryCustomerInfo error: ", e);
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * 基本信息类接口（绿城扩展）
	 * 
	 * （5）客户跟进信息增量更新接口(queryCustomerFollowInfo)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryCustomerFollowInfo")
	public String queryCustomerFollowInfo(Model model, HttpServletRequest request, HttpServletResponse response,
			String body) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryCustomerFollowInfoReqVo reqDto = JSONObject.parseObject(body, QueryCustomerFollowInfoReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryCustomerFollowInfoHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryCustomerFollowInfo error: ", e);
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * 基本信息类接口（绿城扩展PMO）
	 * 
	 * （1）项目信息查询接口(queryProjectInfoPom)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryProjectInfoPom")
	public String queryProjectInfoPom(Model model, HttpServletRequest request, HttpServletResponse response,
			String body) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryProjectInfoPomReqVo reqDto = JSONObject.parseObject(body, QueryProjectInfoPomReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryProjectInfoPomHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryProjectInfoPom error: ", e);
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * “回来了社区” 新增接口
	 * 
	 * （6）房产信息增量接口(queryProjectRoomInfoList)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryProjectRoomInfoList")
	public String queryProjectRoomInfoList(Model model, HttpServletRequest request, HttpServletResponse response,
			String body) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryProjectRoomInfoListReqVo reqDto = JSONObject.parseObject(body, QueryProjectRoomInfoListReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryProjectRoomInfoListHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryProjectRoomInfoList error: ", e);
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * “回来了社区” 新增接口
	 * 
	 * （7） 客户与房产关联关系表增量接口 (queryCustomerRoomList)
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/queryCustomerRoomList")
	public String queryCustomerRoomList(Model model, HttpServletRequest request, HttpServletResponse response,
			String body) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryCustomerRoomListReqVo reqDto = JSONObject.parseObject(body, QueryCustomerRoomListReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryCustomerRoomListHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryCustomerRoomList error: ", e);
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * 项目创建与编辑接口（绿城扩展PMO）
	 * 
	 * (projects)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/v1/sales/projects")
	public void projectsPmo(HttpServletRequest request, HttpServletResponse response, @RequestBody String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String seq = request.getHeader("seq");
		String digest = request.getHeader("digest");
		JSONObject object = new JSONObject();
		try {
			Map<String, String> resultMap = checkAll(seq, digest, false);
			if (resultMap.size() > 0) {
				response.setStatus(Integer.parseInt(resultMap.get("status")));
				return;
			}
			ProjectsPmoReqDto params = JSONObject.parseObject(body, ProjectsPmoReqDto.class);
			if (params.getData() != null) {
				Validator validator = new Validator();
				List<ConstraintViolation> ret = validator.validate(params.getData());
				if (ret != null && ret.size() > 0) {
					object.put("code", "10000001");
					object.put("desc", ret.get(0).getMessage() + "不能为空");
					response.setStatus(500);
					response.getWriter().append(object.toJSONString());
					return;
				}
			}
			ProjectsPmoReqVo reqVo = new ProjectsPmoReqVo();
			reqVo.setParams(params);
			reqVo.setBodyJson(body);
			reqVo.setAdd(true);
			BaseResponseDTO<?> brdto = projectsPmoHander.hander(reqVo);
			ProjectsPmoResDto resDate = (ProjectsPmoResDto) brdto.getResData();
			if (resDate.getCode().equals("000000")) {
				response.setStatus(200);
			} else {
				response.setStatus(500);
				String result = JSONObject.toJSONStringWithDateFormat(brdto.getResData(), "yyyy-MM-dd HH:mm:ss",
						SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect,
						SerializerFeature.WriteNullStringAsEmpty);
				response.getWriter().append(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/v1/sales/projects error: ", e);
			response.setStatus(500);
			object.put("code", "10000002");
			object.put("desc", "参数格式错误");
			response.getWriter().append(object.toJSONString());
		}

	}

	/**
	 * 项目创建与编辑接口（绿城扩展PMO）
	 * 
	 * (projects)
	 * 
	 * @param request
	 * @param response
	 * @param body
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/v1/sales/projects/{projectCode}", method = RequestMethod.PUT)
	public void projectsPmoUpdate(HttpServletRequest request, HttpServletResponse response, @RequestBody String body,
			@PathVariable("projectCode") String projectCode) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String seq = request.getHeader("seq");
		String digest = request.getHeader("digest");
		JSONObject object = new JSONObject();
		try {
			Map<String, String> resultMap = checkAll(seq, digest, false);
			if (resultMap.size() > 0) {
				response.setStatus(Integer.parseInt(resultMap.get("status")));
				return;
			}
			ProjectsPmoReqDto params = JSONObject.parseObject(body, ProjectsPmoReqDto.class);
			ProjectsPmoReqVo reqVo = new ProjectsPmoReqVo();
			reqVo.setParams(params);
			reqVo.setBodyJson(body);
			reqVo.setAdd(false);
			BaseResponseDTO<?> brdto = projectsPmoHander.hander(reqVo);
			ProjectsPmoResDto resDate = (ProjectsPmoResDto) brdto.getResData();
			if (resDate.getCode().equals("000000")) {
				response.setStatus(200);
			} else {
				response.setStatus(500);
				String result = JSONObject.toJSONStringWithDateFormat(brdto.getResData(), "yyyy-MM-dd HH:mm:ss",
						SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect,
						SerializerFeature.WriteNullStringAsEmpty);
				response.getWriter().append(result);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/v1/sales/projects error: ", e);
			response.setStatus(500);
			object.put("code", "10000001");
			object.put("desc", "参数格式错误");
			response.getWriter().append(object.toJSONString());
		}
	}

	@RequestMapping("/v1/sales/project-dynamic-sale/{projectCode}/{month}")
	private void projectDynamicSaleByMonth(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("projectCode") String projectCode, @PathVariable("month") String month) {
		response.setContentType("application/json; charset=utf-8");
		String seq = request.getHeader("seq");
		String digest = request.getHeader("digest");
		Map<String, String> resultMap = checkAll(seq, digest, false);
		if (resultMap.size() > 0) {
			response.setStatus(Integer.parseInt(resultMap.get("status")));
			return;
		}
		JSONObject result = new JSONObject();
		try {
			Response<LevelDynamiSalesData> responseLDSD = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(projectCode, month);
			//Response<LevelDynamiSalesData> responseLDSD = projectServiceFacade.quereyLevelDynamiSalesData(projectCode, month);
			if (responseLDSD.isSuccess()) {
				response.getWriter().append(JSON.toJSONString(responseLDSD.getEntity()));
				return;
			} else {
				response.setStatus(500);
				result.put("code", "10000001");
				result.put("desc", responseLDSD.getResultMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("project-dynamic-sale error: ", e);
			response.setStatus(500);
			result.put("code", "00000006");
			result.put("desc", "系统繁忙");
		}
		try {
			response.getWriter().append(result.toJSONString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean safeCheck() {
		DictionaryDto dictionaryDto = new DictionaryDto();
		dictionaryDto.setDictionaryType(DictionaryTypeEnum.SAFETY_CHECK_SWITCH.getNo());
		ResponseList<Dictionary> list = dictionaryServiceFacade.findByDto(dictionaryDto);
		if (list.isSuccess() && null != list.getEntity() && list.getEntity().size() > 0) {
			Dictionary dictionary = list.getEntity().get(0);
			if (null != dictionary && StringUtils.isNotBlank(dictionary.getDictionaryValue())) {
				String dictionaryValue = dictionary.getDictionaryValue();
				if (dictionaryValue.equals("1")) {
					// 表示开启安全验证
					return true;
				}
			}
		}
		return false;
	}

	private Map<String, String> checkAll(String seq, String digest, Boolean oaVaild) {
		Map<String, String> result = new HashMap<String, String>();
		if (safeCheck()) {
			// 验证参数
			if (!checkParmsFormat(seq, digest)) {
				result.put("status", "401");
				result.put("msg", "请求参数错误");
				return result;
			}
			// 验证验签
			if (!checkSign(seq, digest, oaVaild)) {
				result.put("status", "403");
				result.put("msg", "验签失败");
				return result;
			}
			// 验证是否有效请求
			if (!checkDateSeq(seq)) {
				result.put("status", "403");
				result.put("msg", "无效请求");
				return result;
			}
		}
		return result;
	}

	private boolean checkParmsFormat(String seq, String digest) {
		boolean flag = false;
		if (StringUtils.isBlank(seq) || StringUtils.isBlank(digest)) {
			return flag;
		}
		try {
			String dateValue = seq.substring(0, seq.length() - 6);
			new SimpleDateFormat("yyyyMMddHHmmss").parse(dateValue);
			flag = true;
		} catch (ParseException e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	private boolean checkSign(String seq, String digest, boolean oaVaild) {
		// 请求序列号
		boolean flag = false;
		if (StringUtils.isBlank(seq)) {
			return flag;
		}
		String md5Str = pmoConfig.getClientKey() + seq + pmoConfig.getClientPwd();
		if (oaVaild) {
			md5Str = pmoConfig.getOaClientKey() + seq + pmoConfig.getOaClientPwd();
		}
		String nowdigest = DigestUtils.md5Hex(getContentBytes(md5Str, "utf-8"));
		nowdigest = nowdigest.toUpperCase();
		if (nowdigest.equals(digest)) {
			flag = true;
		}
		return flag;

	}

	private boolean checkDateSeq(String seq) {
		if (StringUtils.isNotBlank(seq)) {
			String dateValue = seq.substring(0, seq.length() - 6);
			Date dateSeq = null;
			try {
				dateSeq = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateValue);
			} catch (ParseException e) {
				return false;
			}

			DictionaryDto dictionaryDto = new DictionaryDto();
			dictionaryDto.setDictionaryType(DictionaryTypeEnum.SAFETY_CHECK_DATA.getNo());
			ResponseList<Dictionary> list = dictionaryServiceFacade.findByDto(dictionaryDto);
			if (list.isSuccess() && null != list.getEntity() && list.getEntity().size() > 0) {
				int date = new Integer(list.getEntity().get(0).getDictionaryValue());
				if (DateUtils.dateDff(dateSeq) > date) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	private static byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
		}
	}

	/**
	 *
	 * @Title: propertyFormsBaseline @Description: (基线业态信息) @param @param
	 *         request @param @param response @param @param body @param @param
	 *         versionProject @param @throws IOException 设定文件 @return void
	 *         返回类型 @throws
	 */
	@RequestMapping(value = "/v1/sales/propertyForms/baseline", method = RequestMethod.POST)
	public void propertyFormsBaseline(HttpServletRequest request, HttpServletResponse response,
			@RequestBody String body) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String seq = request.getHeader("seq");
		String digest = request.getHeader("digest");
		Map<String, String> map = checkAll(seq, digest, false);
		logger.info("开始收集绿城推送业态信息: /v1/sales/propertyForms/baseline", body);
		if (map != null && map.size() > 0) {
			logger.info("检验绿城推送业态状态:", JSONObject.toJSONString(map));
			response.setStatus(new Integer(map.get("status")));
		} else {
			JSONObject object = commonPropertyForms(body, "baseline", seq, digest);
			if (object.get("code").equals("00000000")) {
				response.setStatus(200);
			} else {
				response.setStatus(500);
				String result = JSONObject.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss",
						SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect,
						SerializerFeature.WriteNullStringAsEmpty);
				response.getWriter().append(result);
			}
		}
	}

	/**
	 * @Title: propertyForms @Description: 更新业态信息 @param @param
	 *         request @param @param response @param @param body @param @param
	 *         versionProject 设定文件 @return void 返回类型 @throws
	 */
	@RequestMapping(value = "/v1/sales/propertyForms", method = RequestMethod.POST)
	public void propertyForms(HttpServletRequest request, HttpServletResponse response, @RequestBody String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String seq = request.getHeader("seq");
		String digest = request.getHeader("digest");
		Map<String, String> map = checkAll(seq, digest, false);
		if (map != null && map.size() > 0) {
			response.setStatus(new Integer(map.get("status")));
		} else {
			JSONObject object = commonPropertyForms(body, "propertyForms", seq, digest);
			if (object.get("code").equals("00000000")) {
				response.setStatus(200);
			} else {
				response.setStatus(500);
				String result = JSONObject.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss",
						SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect,
						SerializerFeature.WriteNullStringAsEmpty);
				response.getWriter().append(result);
			}
		}
	}

	/**
	 * @Title: propertyFormsInvalid @Description: 下线接口 HTTP put @param @param
	 *         request @param @param response @param @param body @param @throws
	 *         IOException 设定文件 @return void 返回类型 @throws
	 */
	@RequestMapping(value = "/v1/sales/propertyForms", method = RequestMethod.PUT)
	public void propertyFormsInvalid(HttpServletRequest request, HttpServletResponse response, @RequestBody String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String seq = request.getHeader("seq");
		String digest = request.getHeader("digest");
		JSONObject object = new JSONObject();
		try {
			Map<String, String> map = checkAll(seq, digest, false);
			if (map != null && map.size() > 0) {
				response.setStatus(new Integer(map.get("status")));
			} else {
				if (StringUtils.isEmpty(body)) {
					response.setStatus(500);
					object.put("code", "10000002");
					object.put("desc", "参数不能为空");
					response.getWriter().append(object.toJSONString());
				} else {
					JSONObject mapValue = JSON.parseObject(body);
					Map<String, Object> params = JSONObject.parseObject(mapValue.toJSONString(),
							new TypeReference<Map<String, Object>>() {
							});
					BaseRequestDTO<Map<String, Object>> reqDto = new BaseRequestDTO<Map<String, Object>>();
					reqDto.setParams(params);
					BaseResponseDTO<?> resp = propertyFormsInvalidHander.doBusiness(reqDto);
					ProjectsPmoResDto res = (ProjectsPmoResDto) resp.getResData();
					if (res.getCode().equals("00000000")) {
						response.setStatus(200);
					} else {
						response.setStatus(500);
						String result = JSONObject.toJSONStringWithDateFormat(resp.getResData(), "yyyy-MM-dd HH:mm:ss",
								SerializerFeature.WriteDateUseDateFormat,
								SerializerFeature.DisableCircularReferenceDetect,
								SerializerFeature.WriteNullStringAsEmpty);
						response.getWriter().append(result);
					}

				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("propertyForms error: ", e);
			response.setStatus(500);
			object.put("code", "100001");
			object.put("desc", "参数格式错误");
			response.getWriter().append(object.toString());
		}
	}

	/**
	 *
	 * @Title: commonPropertyForms @Description: 公用 @param @param body @param @param
	 *         interfaceName @param @param seq @param @param digest @param @return
	 *         设定文件 @return JSONObject 返回类型 @throws
	 */
	public JSONObject commonPropertyForms(String body, String interfaceName, String seq, String digest) {
		JSONObject object = new JSONObject();
		try {
			if (StringUtils.isEmpty(body)) {
				logger.info("处理绿城推送业态: body 内容为空!");
				object.put("code", "10000002");
				object.put("desc", "参数不能为空");
				return object;
			} else {
				boolean flag = true;
				List<BaseDataReqDto> params = JSONObject.parseArray(body, BaseDataReqDto.class);
				for (BaseDataReqDto reqVaild : params) {
					Validator validator = new Validator();
					List<ConstraintViolation> ret = validator.validate(reqVaild);
					if (ret != null && ret.size() > 0) {
						object.put("code", "10000002");
						object.put("desc", "参数" + ret.get(0).getMessage());
						flag = false;
						logger.info("检验业态,有错误信息:", JSONObject.toJSONString(object));
						return object;
					}
				}
				if (flag) {
					BaseDataReqVo baseDataReqVo = new BaseDataReqVo();
					baseDataReqVo.setParams(params);
					baseDataReqVo.setInterfaceName(interfaceName);
					BaseResponseDTO<?> brdto = baseDataHander.doBusiness(baseDataReqVo);
					ProjectsPmoResDto val = (ProjectsPmoResDto) brdto.getResData();
					logger.info("得到绿城推送业态结果:", JSONObject.toJSONString(object));
					object.put("code", val.getCode());
					object.put("desc", val.getDesc());
					return object;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.info("绿城推送业态异常:", e);
			object.put("code", "100001");
			object.put("desc", "参数格式错误");
			return object;
		}
		return null;

	}

	/**
	 * OA 组织机构同步接口, 绿城专属接口
	 * 
	 * @param request
	 * @param response
	 * @param body
	 * @exception Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "v1/sales/organization", method = RequestMethod.POST)
	public void oaProjectOrgSyn(HttpServletRequest request, HttpServletResponse response, @RequestBody String body)
			throws Exception {
		OaResponse res = new OaResponse();
		response.setContentType("application/json; charset=utf-8");
		try {
			String seq = request.getHeader("seq");
			String digest = request.getHeader("digest");
			Map<String, String> map = checkAll(seq, digest, true);
			map = new HashMap<String, String>();
			if (map != null && map.size() > 0) {
				response.setStatus(new Integer(map.get("status")));
				res.setResponse(new ResponseOrg(map.get("msg"), map.get("status")));
				response.getWriter().append(JSONObject.toJSONString(res));
			} else {
				OrgOaDataVo vo = JSONObject.parseObject(body, OrgOaDataVo.class);
				BaseRequestDTO reqDto = new BaseRequestDTO();
				reqDto.setParams(vo);
				ResponseOrg responseOrg = (ResponseOrg) oaOrgHander.doBusiness(reqDto).getResData();
				response.setStatus(new Integer(responseOrg.getCode()));
				response.getWriter().append(JSONObject.toJSONString(responseOrg));
				// 记录日志
				PmoLogDto pmoLogDto = new PmoLogDto();
				pmoLogDto.setMerchantId(Long.valueOf(MerchantEnum.GREEN_TOWN.getNo()));
				pmoLogDto.setDirection("3");
				if (responseOrg.getCode().equals("200")) {// 成功
					pmoLogDto.setStatus("1");
				} else {
					pmoLogDto.setStatus("2");
				}
				pmoLogDto.setRequestParams(body);
				pmoLogDto.setDelFlag("0");
				pmoLogDto.setInterfaceName("OA数据同步");
				pmoLogDto.setReturnResult(JSON.toJSONString(responseOrg));
				//非成功数据才记录数据库,过滤掉成功接收的内容
				//5分钟连推三条,而且是同一时间,绿城推送此数据以前不这样的.
				//只有失败了才会重新再推送.
				if(!"1".equals(pmoLogDto.getStatus())){
					pmoLogServiceFacade.save(pmoLogDto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("v1/sales/organization error: ", e);
			response.setStatus(500);
			res.setResponse(new ResponseOrg("同步接口处理异常,请联系接口负责人!", "500"));
			response.getWriter().append(JSONObject.toJSONString(res));
			e.printStackTrace();
		}
	}

	/**
	 * 渠道->M2转客接口 M2向渠道提供项目信息
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/channelToM2")
	public String channelToM2(Model model, HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		ChannelToM2ReqVo reqDto = JSONObject.parseObject(body, ChannelToM2ReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(channelToM2Hander.hander(reqDto), "yyyy-MM-dd HH:mm:ss",
				SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteNullStringAsEmpty);
		response.getWriter().append(result);
		return null;
	}

	@RequestMapping("/mcQueryProject")
	public void mcQueryProject(Model model, HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		MCQueryProjectReqVo reqDto = JSONObject.parseObject(body, MCQueryProjectReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(mcQueryProjectHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			// result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			logger.error("mcQueryProject error: ", e);
			e.printStackTrace();
		}
		response.getWriter().append(result);
	}

	/**
	 * M2向渠道提供客户唯一性校验
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/mcCusUniqueValidate")
	public void mcCusUniqueValidate(Model model, HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		MCCusUniqueReqVo reqDto = JSONObject.parseObject(body, MCCusUniqueReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(mcCusUniqueHander.hander(reqDto), "yyyy-MM-dd HH:mm:ss",
				SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteNullStringAsEmpty);
		try {
			// result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			logger.error("mcCusUniqueValidate error: ", e);
			e.printStackTrace();
		}
		response.getWriter().append(result);
	}

	/**
	 * 
	 * queryCustomerTagList:(回来了社区，客户标签查询). <br/>
	 * 
	 * @author Administrator
	 * @param request
	 * @param response
	 * @param body
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "queryCustomerTagList")
	public String queryCustomerTagList(HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryCustomerTagReqVo reqDto = JSONObject.parseObject(body, QueryCustomerTagReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryCustomerTagListHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			logger.error("queryCustomerTagList error: ", e);
			e.printStackTrace();
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * 
	 * queryCustomerTagList:(回来了社区，客户问卷查询). <br/>
	 * 
	 * @author Administrator
	 * @param request
	 * @param response
	 * @param body
	 */
	@RequestMapping(value = "queryCustomerQuestionnaireList")
	public String queryCustomerQuestionnaireList(HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryCustomerTagReqVo reqDto = JSONObject.parseObject(body, QueryCustomerTagReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryCustomerQuestionnaireListHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		// System.out.println("queryCustomerQuestionnaireList====" + result);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			logger.error("queryCustomerQuestionnaireList error: ", e);
			e.printStackTrace();
		}
		response.getWriter().append(result);
		return null;
	}

	/**
	 * queryAgentListByCustomerPhone
	 * 
	 * @author jzliu
	 * @param request
	 * @param response
	 * @param body
	 */
	@RequestMapping(value = "queryAgentListByCustomerPhone")
	public String queryAgentListByCustomerPhone(HttpServletRequest request, HttpServletResponse response, String body)
			throws IOException {
		response.setContentType("application/json; charset=utf-8");
		QueryAgentListByCustomerPhoneReqVo reqDto = JSONObject.parseObject(body,
				QueryAgentListByCustomerPhoneReqVo.class);
		String result = JSONObject.toJSONStringWithDateFormat(queryAgentListByCustomerPhoneHander.hander(reqDto),
				"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty);
		try {
			result = RSAUtil.encryptByPublicKeyBASE64(result.getBytes());
		} catch (Exception e) {
			logger.error("queryAgentListByCustomerPhone error: ", e);
			e.printStackTrace();
		}
		response.getWriter().append(result);
		return null;
	}
}
